package com.zqh.apiuserlogin.service.impl;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zqh.apiuserlogin.redis.RedisUtil;
import com.zqh.apiuserlogin.service.UsersLoginService;
import com.zqh.myfmmall.clients.UserQueryClient;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.rowbeans.entity.Users;
import com.zqh.myfmmall.utils.JwtUtil;
import com.zqh.myfmmall.utils.Md5Utile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;


/**
 * 用户 (Users)表服务实现类
 *
 * @author KONO 曾淇杭哒！
 * @since 2022-01-20 02:35:50
 */
@Slf4j
@Service("usersService")
public class UsersLoginServiceImpl implements UsersLoginService{
    @Autowired
    private UserQueryClient userQueryClient;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result login(Users user) {
//        通过feign调用服务
        Result result = userQueryClient.queryUser(user);
        //调用服务出错
        if (!result.getSuccess()){
            return Result.internalServerError();
        }
        //返回的user为空则说明用户不存在，若存在则查看密码是否正确
        if (result.getData() != null) {
            Users targetUser = JSON.parseObject(JSON.toJSONString(result.getData()), Users.class);
            //校验密码
            if (targetUser.getPassword().equals(Md5Utile.MD5Encode(user.getPassword()))) {
                HashMap<String, Object> claimsMap = new HashMap<>();
                claimsMap.put("userId",targetUser.getUserId());
                String token = JwtUtil.generate(claimsMap);
                //通过redis实现分布式会话
                boolean success = redisUtil.set(token, targetUser.getUserId(), RedisUtil.DEFAULT_TIMEOUT);
                return success ? Result.success("登录成功！",token) : Result.internalServerError();
            }else {
                return Result.fail("密码错误");
            }
        }
        return Result.fail("用户不存在");

    }
}

